package seri

import (
	"encoding/json"
	log "github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/bson"
)

var SerisRegister map[int32]Serialization = make(map[int32]Serialization)

const (
	SERIAL_TYPE_JSON_CODE = 0
	SERIAL_TYPE_BSON_CODE = 2
)

func init() {
	RegisterSeri(SERIAL_TYPE_JSON_CODE, new(JsonSerialization))
	RegisterSeri(SERIAL_TYPE_BSON_CODE, new(BsonSerialization))
}

func RegisterSeri(key int32, seri Serialization) {
	SerisRegister[key] = seri
}
func Get(key int32) (Serialization, bool) {
	s, f := SerisRegister[key]
	return s, f
}

var _ Serialization = new(JsonSerialization)
var _ Serialization = new(BsonSerialization)

type Serialization interface {
	From(data []byte, obj any) error
	To(obj any) ([]byte, error)
}

type JsonSerialization struct {
}

func (j JsonSerialization) From(data []byte, obj any) error {
	err := json.Unmarshal(data, obj)
	if err != nil {
		log.Error(err)
	}
	return err
}

func (j JsonSerialization) To(obj any) ([]byte, error) {
	data, err := json.Marshal(obj)
	if err != nil {
		log.Error(err)
	}
	return data, err
}

type BsonSerialization struct {
}

func (j BsonSerialization) From(data []byte, obj any) error {
	var err = bson.Unmarshal(data, obj)
	if err != nil {
		log.Error(err)
	}
	return err
}

func (j BsonSerialization) To(obj any) ([]byte, error) {
	data, err := bson.Marshal(obj)
	if err != nil {
		log.Error(err)
	}
	return data, err
}
